<template>
  <div class="container">
    <!-- 钱包连接按钮 -->
    <div class="wallet-section">
      <el-button v-if="!isConnected" type="primary" :icon="Connection" @click="connect">
        连接钱包
      </el-button>
      <div v-else class="connected-info">
        钱包地址：<el-tag type="success" size="large">{{ shortenAddress }}</el-tag>
        <el-button type="warning" :icon="Close" @click="disconnect">断开连接</el-button>
      </div>
    </div>

    <div v-if="isConnected">
      <!-- 网络信息显示 -->
      <el-card shadow="hover">
        <template #header>
          <span>网络信息</span>
        </template>
        <el-form label-suffix="：">
          <el-form-item label="当前网络名称">{{ networkName }}</el-form-item>
          <el-form-item label="ETH余额">{{ ethBalance }}</el-form-item>
          <el-form-item label="ERC-20 Token合约地址">{{ erc20Token }}</el-form-item>
        </el-form>
      </el-card>

      <!-- 转账表单 -->
      <el-card shadow="hover" style="margin-top: 30px;">
        <template #header>
          <span>转账表单</span>
        </template>
        <el-form ref="transferFormRef" :model="transferForm" label-width="120px" :rules="rules">
          <el-form-item label="转账类型" prop="type">
            <el-radio-group v-model="transferForm.type">
              <el-radio label="ETH">ETH</el-radio>
              <el-radio label="ERC-20">ERC-20 Token</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="接收地址" prop="address">
            <el-input v-model="transferForm.address" placeholder="填写收款人的以太坊地址" />
          </el-form-item>

          <el-form-item label="转账金额" prop="amount">
            <el-input-number 
              v-model="transferForm.amount"
              :min="0"
              :precision="4"
              controls-position="right"
              placeholder="填写转账金额"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm(transferFormRef)">发送</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 交易提示 -->
    <el-dialog v-model="showDialog" title="交易结果" width="30%">
      <span>{{ dialogMessage }}</span>
      <template #footer>
        <el-button @click="showDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from "vue"
import { ElLoading, ElMessage } from "element-plus"
import { Close, Connection } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { isWalletInstalled, connectWallet } from './utils/wallet'

// 模拟数据
const MOCK_DATA = {
  network: 'Sepolia Testnet',
  ethBalance: 1.5234,
  erc20Token: 1000,
  erc20Address: '0x8d12A197cB00D4747a1fe03395095CE2A5CC6819'
}

// 响应式状态
const isConnected = ref(false)
const currentAddress = ref('')
const networkName = ref('')
const ethBalance = ref(0)
const erc20Token = ref(0)
const transferFormRef = ref<FormInstance>()

const transferForm = ref({
  type: 'ETH',
  address: '',
  amount: 0
})

const rules = ref({
  type: [
    { required: true, message: '请选择转账类型', trigger: ['change'] },
  ],
  address: [
    { required: true, message: '请输入收款人的以太坊地址', trigger: ['change', 'blur'] }
  ],
  amount: [
    { required: true, message: '请输入转账金额', trigger: ['change', 'blur'] },
  ]
})

const showDialog = ref(false)
const dialogMessage = ref('')

// 计算属性
const shortenAddress = computed(() => {
  if (!currentAddress.value) return ''
  const start = currentAddress.value.slice(0, 6)
  const end = currentAddress.value.slice(-4)
  return `${start}...${end}`
})

// 方法
const connect = async () => {
  if (!isWalletInstalled()) {
    ElMessage.error('请确保已经安装MetaMask钱包')
    return;
  }
  const loading = ElLoading.service({
    lock: true,
    text: '连接中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    isConnected.value = true;
    await connectWallet();
    currentAddress.value = '0x1234567890abcdef1234567890abcd'
    networkName.value = MOCK_DATA.network
    ethBalance.value = MOCK_DATA.ethBalance
    erc20Token.value = MOCK_DATA.erc20Token
    console.log('erc20Token', erc20Token.value);
  } catch (error) {
    console.error(error);
    isConnected.value = false
    alert(`连接失败: ${error}`);
  } finally {
    loading.close()
  }
}

const disconnect = () => {
  isConnected.value = false
  currentAddress.value = ''
  networkName.value = ''
  ethBalance.value = 0
  erc20Token.value = 0
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        const loading = ElLoading.service({
          lock: true,
          text: '发送交易中...',
          background: 'rgba(0, 0, 0, 0.7)',
        })
        // 模拟交易发送
        await new Promise(resolve => setTimeout(resolve, 1500))
        loading.close()
        showDialog.value = true
        dialogMessage.value = '交易已发送，等待确认中...'
        
        // 重置表单
        transferForm.value = {
          type: 'ETH',
          address: '',
          amount: 0
        }
      } catch (error) {
        ElMessage.error('Transaction failed')
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>

<style scoped>
.wallet-section {
  margin-bottom: 30px;
  text-align: center;
}

.connected-info {
  display: flex;
  gap: 10px;
  justify-content: center;
  align-items: center;
}

.transfer-form {
  margin-top: 30px;
}

.el-input-number {
  width: 200px;
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }
}
</style>
